import { fileURLToPath, URL } from "node:url"
import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"
import vueDevTools from "vite-plugin-vue-devtools"

// https://vite.dev/config/
export default defineConfig({
  plugins: [vue(), vueDevTools()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  server: {
    proxy: {
      // "/api": {
      //   target: "http://localhost:8000/",
      //   changeOrigin: true,
      // },
      "/kimiapi": {
        target: "https://api.moonshot.cn",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/kimiapi/, ""),
      },
    },
  },
  build: {
    // 输出目录
    outDir: "dist",
    // 静态资源目录
    assetsDir: "assets",
    // 资源内联阈值
    assetsInlineLimit: 4096,
    // 启用 CSS 代码分割
    cssCodeSplit: true,
    // 启用源码映射（生产环境建议关闭）
    sourcemap: false,
    chunkSizeWarningLimit: 1000,
    // 压缩配置
    minify: "esbuild",
    // terserOptions: {
    //   compress: {
    //     drop_console: true, // 移除 console
    //     drop_debugger: true, // 移除 debugger
    //   },
    // },
    rollupOptions: {
      output: {
        // 手动分块策略
        manualChunks: {
          // Vue 相关库
          "vue-vendor": ["vue", "vue-router"],
          // 状态管理
          "pinia-vendor": ["pinia"],
          // UI 组件库
          "ui-vendor": ["@fortawesome/fontawesome-free"],
          // 工具库
          "utils-vendor": ["axios"],
          // 编辑器
          "editor-vendor": ["md-editor-v3"],
        },
        // 文件名配置
        chunkFileNames: "assets/js/[name]-[hash].js",
        entryFileNames: "assets/js/[name]-[hash].js",
        assetFileNames: (assetInfo) => {
          const info = assetInfo.name.split(".")
          const ext = info[info.length - 1]
          if (/\.(css)$/.test(assetInfo.name)) {
            return `assets/css/[name]-[hash].${ext}`
          }
          if (/\.(png|jpe?g|gif|svg|ico|webp)$/.test(assetInfo.name)) {
            return `assets/images/[name]-[hash].${ext}`
          }
          if (/\.(woff2?|eot|ttf|otf)$/.test(assetInfo.name)) {
            return `assets/fonts/[name]-[hash].${ext}`
          }
          if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)$/.test(assetInfo.name)) {
            return `assets/media/[name]-[hash].${ext}`
          }
          return `assets/[name]-[hash].${ext}`
        },
      },
    },
  },
  // 优化依赖预构建
  optimizeDeps: {
    include: ["vue", "vue-router", "pinia", "axios"],
  },
})
